package dp.ua.epic.webapp;

import dp.ua.epic.pages.Choose;
import dp.ua.epic.pages.Start;
import epic.domain.PathDecision;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.WebResponse;
import org.apache.wicket.protocol.http.WebRequestCycle;

/**
 * Custom request cycle that represent filter
 * 
 * @author Chris
 * @date 31.01.2011 18:04:35
 */
public class EpicRequestCycle extends WebRequestCycle {

    public EpicRequestCycle(WebApplication application, WebRequest request, WebResponse response) {
        super(application, request, response);
    }

    @Override
    protected void onBeginRequest() {
        if ((sessionIsEmpty() && requestPageAreNotStart())) {
            setRedirect(true);
            setResponsePage(Start.class);
        } else if (requestPageAreFatePage() && userDoesNotChooseDestiny()) {
            setRedirect(true);
            setResponsePage(Choose.class);
        } else {
            super.onBeginRequest();
        }
    }

    private boolean requestPageAreFatePage() {
        return request.getPath().startsWith("fate");
    }

    private boolean userDoesNotChooseDestiny() {
        return ((EpicSession) getSession()).getHero().getDecision() == PathDecision.UNDEFINED;
    }

    private boolean sessionIsEmpty() {
        return ((EpicSession) getSession()).isHeroInitialized() == false;
    }

    private boolean requestPageAreNotStart() {
        String requestPath = request.getPath();
        return !(requestPath.startsWith("start") || requestPath.isEmpty());
    }
}
